package cn.virens.common.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

public class ApplicationContextUtil {

    /**
     * 如果 bean 是 ApplicationContextAware 的实现类，就将ApplicationContext 注入
     *
     * @param <E>                bean's type
     * @param bean               bean
     * @param applicationContext applicationContext
     * @throws BeansException 注入异常
     */
    public static <E> void inject(E bean, ApplicationContext applicationContext) throws BeansException {
        if (bean instanceof ApplicationContextAware) {
            ((ApplicationContextAware) bean).setApplicationContext(applicationContext);
        } else if (bean instanceof Iterable<?>) {
            for (Object _bean : (Iterable<?>) bean) {
                inject(_bean, applicationContext);
            }
        } else if (bean instanceof Map<?, ?>) {
            for (Object _bean : ((Map<?, ?>) bean).values()) {
                inject(_bean, applicationContext);
            }
        }
    }

    /**
     * 如果 bean 是 InitializingBean 的实现类，就将调用afterPropertiesSet
     *
     * @param <E>  bean's type
     * @param bean bean
     * @throws Exception 初始化异常
     */
    public static <E> void init(E bean) throws Exception {
        if (bean instanceof InitializingBean) {
            ((InitializingBean) bean).afterPropertiesSet();
        } else if (bean instanceof Iterable<?>) {
            for (Object _bean : (Iterable<?>) bean) {
                init(_bean);
            }
        } else if (bean instanceof Map<?, ?>) {
            for (Object _bean : ((Map<?, ?>) bean).values()) {
                init(_bean);
            }
        }
    }
}
